#!/bin/bash
SERVICE="nginx"
LOG_LEVEL="INFO"  # 可设置为DEBUG/INFO/WARN/ERROR

# 日志函数
log() {
    local level=$1
    local msg=$2
    if [[ "$level" == "DEBUG" && "$LOG_LEVEL" != "DEBUG" ]]; then return; fi
    echo "[$(date '+%F %T')] [$level] $msg" | tee -a /var/log/service_monitor.log
}

# 多条件服务检查
if systemctl is-active "$SERVICE" >/dev/null; then
    log "INFO" "$SERVICE 运行正常"
    # 附加检查：端口监听
    if netstat -tuln | grep -q ":80 "; then
        log "DEBUG" "80端口监听正常"
    else
        log "ERROR" "服务运行但80端口未监听！"
    fi
else
    log "WARN" "$SERVICE 未运行，尝试启动..."
    systemctl start "$SERVICE" && log "INFO" "启动成功" || log "ERROR" "启动失败！"
fi
#功能,动态日志级别控制 ,嵌套条件检查（服务状态+端口） ,自动修复尝试 